<?php

// +----------------------------------------------------------------------

namespace app\api\controller;

use app\common\controller\Api;
use app\user\model\Member as MemberModel;
use util\Wxsdk;
use think\Db;
/**
 * 用户首页控制器
 * @package app\api\controller
 */
class Wechat extends Api
{

	/**
	 * @name 获取access_token
	 * @method POST
	 * @param time 当前时间戳
	 * @param sign 签名 md5($key.$time)
	 * @return json ( expire_time & access_token )
	 */
	public function token()
	{
		if ($this->request->isPost()) {
			// 获取数据
			$data = $this->request->post();
			if(!isset($data['sign']) || !isset($data['time'])) $this->success('请求成功');
			$sign = $data['sign'];
			$time = $data['time'];
			$now  = time() - (int)$time;
			if($now >= 60 || $now < -60) $this->error('时间格式错误', $now);
			$key = 'NdiWENBuS5HSQRwAr-zzmind-PUBLIC';
			$mysign = md5($key.$time);
			if($mysign != $sign || !$sign) $this->error('签名错误');
			$wxsdk = new Wxsdk;
			$token =  $wxsdk->getToken();
			if ($token == false) {
				$this->error($wxsdk->getError());
			}
			$this->success('获取成功', $token);
		}else{
			$this->success('连接成功');
		}
	}
	/**
	 * 获取授权code
	 * @param string url 回调路径
	 * @return redirect 附带code并跳转回调路径
	 */
	public function code($url = '', $recode = 'ok', $mod = 'snsapi_base')
	{
		if ($url !== ''){
			if (strripos($url,'http') === 0){
				cache($url, $recode, 30);
				$url = urlencode($url);
				$code = real_url('api/wechat/code');
				$code = urlencode($code);
				$api = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wechat.appid').'&redirect_uri='.$code.'&response_type=code&scope='.$mod.'&state='.$url.'#wechat_redirect';
				header("Location: $api");
			}else{
				$this->error('回调路径不合法');
			}
		}else{
			// 获取数据
			$data = $this->request->param();
			if (isset($data['code']) && isset($data['state'])){
				//回调给外部链接
				$reurl = urldecode($data['state']);
				$url= $reurl.'?code='.$data['code'].'&state='.cache($reurl);
				header("Location: $url");
			}else{
				$this->error('接口回调失败');
			}
		}
		$this->success('接口请求成功');
	}
	/**
	 * 通过小程序CODE获取openid
	 * @param string code 授权code
	 * @return array token
	 */
	public function userAuth($code = '')
	{
		if (request()->isPost()){
			if ($code !== ''){
				$config = config('wechat.wxapp');
				$api = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['appsecret'].'&js_code='.$code.'&grant_type=authorization_code';
				$return = json_decode(get_curls($api), true);
				if (!isset($return['errcode'])){ //成功回调
					$map = [
						['status', '=', 1],
					];
					if (isset($return['unionid']) && $return['unionid'] != ''){
						$map[] = ['unionid', '=', $return['unionid']];
					} else {
						$map[] = ['wxapp_openid', '=', $return['openid']];
					}
					$return['uid'] = '';
					$uid = MemberModel::where($map)->value('id');
					if ($uid) $return['uid'] = $uid;
					$return['expire_time'] = time() + 3600*24*3; //有效期3天
					$return['deviceType'] = $this->deviceType;
					$token = md5($return['openid'].$return['session_key'].$return['expire_time']);
					unset($return['session_key']);
					cache($token, $return, 3600*24*3);
					$this->success('登录成功', $token);
				} else {
					$this->error($return['errmsg']);
				}
			}else{
				$this->error('登录失败');
			}
		}
		$this->success('接口请求成功');
	}
	/**
	 * 更新用户信息
	 * @param string info 用户信息
	 * @return array token
	 */
	public function userInfo()
	{
		if (request()->isPost()){
			if (empty($this->token)) $this->error(['code' => 10001, 'msg' => '登录已失效!']);
			$auth = cache($this->token);
			if (!$auth) $this->error(['code' => 10001, 'msg' => '登录已失效!']);
			$info = request()->post();
			if (!isset($info['avatarUrl']) || !isset($info['nickName'])) $this->error('用户信息错误');
			// 截取openid字段7-16位
			$username = 'wx_'.mb_substr($auth['openid'], 6, 10);
			if ($this->emoji($info['nickName'])) $info['nickName'] = $username;
			$userfile['nickname'] = $info['nickName'];
			
			$userfile['wxapp_openid'] = $auth['openid'];
			$userfile['key']	= $auth['openid'];
			$userfile['role']	= 'wxapp';
			if (isset($auth['unionid']) && $auth['unionid'] != '') $userfile['unionid'] = $auth['unionid'];
			$userfile['avatar_img'] = $info['avatarUrl'];
			
			$userfile['sex'] = $info['gender'];
			$MemberModel = new MemberModel;
			$result = $MemberModel->saveData($userfile, false);
			if($result === false){
				$this->error($MemberModel->getError());
			}
			$auth['uid'] = $result;
			cache($this->token, $auth, $auth['expire_time'] - time());
			$user = $MemberModel->find($auth['uid']);
			if ($user) {
				$return = $user->visible(['id','nickname','wxapp_openid','avatar_img','sex'])->toArray();
				$this->success('获取成功', $return);
			} else {
				$this->error('登录失败');
			}
			
		}
		$this->success('接口请求成功');
	}
	// //获取access_token
	// public function gettoken()
	// {
	// 	$api	= 'https://zzpay.zzmind.com/api/wechat/token';
	// 	$key	= 'NdiWENBuS5HSQRwAr-zzmind-PUBLIC';
	// 	$time	= time();
	// 	$sign 	= md5($key.$time);
	// 	$post = [
	// 		'time'	=> $time,
	// 		'sign'	=> $sign,
	// 	];
	// 	$result = post_curls($api, $post);
	// 	$result = json_decode($result, true);
	// 	return $result['data'];
	// }
	/**
	 * 判断是否存在emoji表情
	 */
	private function emoji($str)
	{
		$length = mb_strlen($str);
		$array = [];
		for ($i=0; $i<$length; $i++) {
			$array[] = mb_substr($str, $i, 1, 'utf-8');
			if( strlen($array[$i]) >= 4 ){
				return true;
			}
		}  
		return false;
	}
}
